package com.tsing.cli.system.aspect;

import cn.hutool.extra.servlet.JakartaServletUtil;
import cn.hutool.http.useragent.UserAgentUtil;
import com.tsing.cli.common.dto.CustomUserDetails;
import com.tsing.cli.system.service.ILogService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

/**
 * 日志切面类
 *
 * @author TheTsing
 */
@Aspect
@Order(2)
@Component
@RequiredArgsConstructor
public class LogAspect {

    @Value("${log.support:false}")
    private Boolean logSupport;

    private final ILogService logService;

    private final ThreadLocal<Long> currentTime = new ThreadLocal<>();

    @Pointcut("@annotation(com.tsing.cli.common.annotation.Logger)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        if (!logSupport) {
            return joinPoint.proceed();
        }
        currentTime.set(System.currentTimeMillis());
        Object result = joinPoint.proceed();
        long requestTime = System.currentTimeMillis() - currentTime.get();
        currentTime.remove();
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String username = null;
        if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof CustomUserDetails customUserDetails) {
            username = customUserDetails.getUsername();
        }
        logService.save(username, JakartaServletUtil.getClientIP(request), UserAgentUtil.parse(request.getHeader("User-Agent")), requestTime, joinPoint);
        return result;
    }

    @AfterThrowing(value = "pointcut()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Throwable e) {
        if (logSupport) {
            long requestTime = System.currentTimeMillis() - currentTime.get();
            currentTime.remove();
            HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
            String username = null;
            if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof CustomUserDetails customUserDetails) {
                username = customUserDetails.getUsername();
            }
            logService.save(username, JakartaServletUtil.getClientIP(request), UserAgentUtil.parse(request.getHeader("User-Agent")), requestTime, joinPoint, e);
        }
    }

}
